package nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by yu756 on 2020/1/5 21:38
 */
public class NioClient {

    public static void main(String[] args) throws Exception {

        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();

        // 设置非阻塞模式
        socketChannel.configureBlocking(false);
        // 服务器的ip port
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        // 连接服务器
        if (!socketChannel.connect(inetSocketAddress)) {

            while (!socketChannel.finishConnect()) {
                System.out.println("连接需要事件，客户端不会阻塞，可以做其他工作");
            }
        }
        // 连接成功 发送数据
        String str = "hello world ";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        // 将buffer数据写入到channel
        socketChannel.write(buffer);
        System.in.read();

    }

}
